import React, {useEffect, useState} from 'react';
import {Edit2, Lock, Shield, Trash2, UserPlus} from 'lucide-react';
import DeleteConfirmModal from '../../components/modals/DeleteConfirmModal';
import RoleManageModal from '../../components/modals/RoleManageModal';
import {Req} from '../../util/fetch';

interface Permission {
    id: string;
    name: string;
    description: string;
    group: string;
}

interface Role {
    id: number;
    name: string;
    remark: string;
    permissions: string[];
    userCount: number;
}

// 系统权限列表
const systemPermissions: Permission[] = [
    // 用户管理权限
    {
        id: 'user.view',
        name: '查看用户',
        description: '查看系统用户列表和详情',
        group: '用户管理'
    },
    {
        id: 'user.manage',
        name: '管理用户',
        description: '创建、编辑和删除用户',
        group: '用户管理'
    },
    //培训订单
    {
        id: 'order.view',
        name: '查看培训订单',
        description: '查看详情',
        group: '培训订单管理'
    },
    {
        id: 'order.manage',
        name: '管理培训订单',
        description: '管理订单数据',
        group: '培训订单管理'
    },
    // 活动管理权限
    {
        id: 'training.view',
        name: '查看活动',
        description: '查看训练活动列表和详情',
        group: '活动管理'
    },
    {
        id: 'training.manage',
        name: '管理活动',
        description: '创建、编辑和删除训练活动',
        group: '活动管理'
    },
    // 评论管理权限
    {
        id: 'comment.view',
        name: '查看评论',
        description: '查看评论列表',
        group: '评论管理'
    },
    {
        id: 'comment.manage',
        name: '管理评论',
        description: '删除评论',
        group: '评论管理'
    },
    // 媒体管理权限
    {
        id: 'media.view',
        name: '查看媒体',
        description: '查看媒体文件',
        group: '媒体管理'
    },
    {
        id: 'media.manage',
        name: '管理媒体',
        description: '上传、编辑和删除媒体文件',
        group: '媒体管理'
    },
    // 勋章管理权限
    {
        id: 'medal.view',
        name: '查看勋章',
        description: '查看勋章列表和获得者',
        group: '勋章管理'
    },
    {
        id: 'medal.manage',
        name: '管理勋章',
        description: '创建、编辑勋章和发放勋章',
        group: '勋章管理'
    },
    // 系统设置权限
    {
        id: 'setting.view',
        name: '查看设置',
        description: '查看系统设置',
        group: '系统设置'
    },
    {
        id: 'setting.manage',
        name: '管理设置',
        description: '修改系统设置',
        group: '系统设置'
    },
    // 角色管理权限
    {
        id: 'role.view',
        name: '查看角色',
        description: '查看角色列表和权限',
        group: '角色管理'
    },
    {
        id: 'role.manage',
        name: '管理角色',
        description: '创建、编辑和删除角色',
        group: '角色管理'
    }
];

// 预设角色
// const mockRoles: Role[] = [
//   {
//     id: 1,
//     name: '系统管理员',
//     description: '拥有系统所有权限',
//     permissions: systemPermissions.map(p => p.id),
//     userCount: 3
//   },
//   {
//     id: 2,
//     name: '评论管理员',
//     description: '管理系统评论',
//     permissions: ['comment.view', 'comment.manage'],
//     userCount: 5
//   },
//   {
//     id: 3,
//     name: '媒体管理员',
//     description: '管理系统媒体文件',
//     permissions: ['media.view', 'media.manage'],
//     userCount: 4
//   },
//   {
//     id: 4,
//     name: '活动管理员',
//     description: '管理训练活动',
//     permissions: ['training.view', 'training.manage'],
//     userCount: 6
//   }
// ];

export default function AdminRoles() {
    const [roles, setRoles] = useState<Role[]>([]);
    const [showManageModal, setShowManageModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [selectedRole, setSelectedRole] = useState<Role | null>(null);
    const [modalMode, setModalMode] = useState<'add' | 'edit'>('add');

    const handleAddRole = () => {
        setModalMode('add');
        setSelectedRole(null);
        setShowManageModal(true);
    };

    const handleEditRole = (role: Role) => {
        setModalMode('edit');
        setSelectedRole(role);
        setShowManageModal(true);
    };

    const handleDeleteRole = (role: Role) => {
        setSelectedRole(role);
        setShowDeleteModal(true);
    };

    const handleSaveRole = async (roleData) => {
        // if (modalMode === 'add') {
        //   setRoles([...roles, { ...roleData, id: Math.max(...roles.map(r => r.id)) + 1 }]);
        // } else {
        //   setRoles(roles.map(role =>
        //     role.id === selectedRole?.id ? { ...role, ...roleData } : role
        //   ));
        // }
        console.log('handleSaveRole', roleData);
        const res = await Req(modalMode == 'add' ? '/sysRole/add' : '/sysRole/edit', {
            method: modalMode == 'add' ? 'POST' : 'PUT',
            body: {...roleData, permission: roleData.permissions.join('@')},
            headers: undefined
        })
        if (res.success) {
            queryList()
            alert(res.message)
        } else {
            alert(res.message)
        }
        setShowManageModal(false);
        setSelectedRole(null);
    };

    const handleConfirmDelete = () => {
        if (selectedRole) {
            setRoles(roles.filter(role => role.id !== selectedRole.id));
        }
        setShowDeleteModal(false);
        setSelectedRole(null);
    };

    const queryList = async () => {
        const res = await Req(`/sysRole/list`)
        if (res.success) {
            setRoles(res.data)
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        queryList()
    }, [])

    return (
        <div>
            <div className="mb-8">
                <h1 className="text-2xl font-bold text-gray-900">权限管理</h1>
                <p className="text-gray-500">管理系统角色和权限</p>
            </div>

            {/* 工具栏 */}
            <div className="flex justify-end mb-6">
                <button
                    onClick={handleAddRole}
                    className="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                    <UserPlus className="w-5 h-5 mr-2"/>
                    添加角色
                </button>
            </div>

            {/* 角色列表 */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {roles.map(role => (
                    <div
                        key={role.id}
                        className="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-all duration-300"
                    >
                        <div className="flex items-center justify-between mb-4">
                            <div className="flex items-center space-x-3">
                                <div className="p-2 bg-blue-100 text-blue-600 rounded-lg">
                                    <Shield className="w-5 h-5"/>
                                </div>
                                <div>
                                    <h3 className="text-lg font-semibold text-gray-900">{role.name}</h3>
                                    <p className="text-sm text-gray-500">{role.remark}</p>
                                </div>
                            </div>
                            <div className="flex items-center space-x-2">
                                <button
                                    onClick={() => handleEditRole(role)}
                                    className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                >
                                    <Edit2 className="w-5 h-5"/>
                                </button>
                                {role.name !== '系统管理员' && (
                                    <button
                                        onClick={() => handleDeleteRole(role)}
                                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                    >
                                        <Trash2 className="w-5 h-5"/>
                                    </button>
                                )}
                            </div>
                        </div>

                        <div className="space-y-4">
                            {/* 权限组统计 */}
                            <div className="bg-gray-50 rounded-lg p-4">
                                <div className="flex items-center justify-between mb-2">
                                    <h4 className="text-sm font-medium text-gray-700">权限概览</h4>
                                    <span className="text-sm text-gray-500">
                    {role.permissions.length} 项权限
                  </span>
                                </div>
                                <div className="space-y-2">
                                    {Array.from(new Set(role.permissions.map(p =>
                                        systemPermissions.find(sp => sp.id === p)?.group
                                    ))).map(group => (
                                        <div
                                            key={group}
                                            className="flex items-center text-sm text-gray-600"
                                        >
                                            <Lock className="w-4 h-4 mr-2"/>
                                            {group}
                                        </div>
                                    ))}
                                </div>
                            </div>

                            <div className="flex items-center justify-between text-sm">
                                <span className="text-gray-500">使用该角色的用户数</span>
                                <span className="font-medium text-gray-900">{role.userCount} 人</span>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {/* 角色管理模态框 */}
            {showManageModal && (
                <RoleManageModal
                    mode={modalMode}
                    role={selectedRole}
                    permissions={systemPermissions}
                    onClose={() => {
                        setShowManageModal(false);
                        setSelectedRole(null);
                    }}
                    onSave={handleSaveRole}
                />
            )}

            {/* 删除确认模态框 */}
            {showDeleteModal && selectedRole && (
                <DeleteConfirmModal
                    title="删除角色"
                    message={`确定要删除"${selectedRole.name}"角色吗？此操作不可恢复。`}
                    onConfirm={handleConfirmDelete}
                    onCancel={() => {
                        setShowDeleteModal(false);
                        setSelectedRole(null);
                    }}
                />
            )}
        </div>
    );
}